﻿<?php
/**
 * This is the file to define LogHandler.
 * 
 * @author	Justin Yoo
 * @version	0.0.1.0001
 * @package	KYR.Core
 * 
 */

//	Checks if this file is called within the framework; otherwise terminates.
if (!defined("IS_FRAMEWORK") || !IS_FRAMEWORK)	header("Location: http://".$_SERVER["HTTP_HOST"]."/error/404");

//	Imports relevant files.
require_once CORE_PATH."KYR.Core.BaseHandler.php";

/**
 * This is class LogHandler that processes log file.
 *
 * Processes log file.
 * 
 * @author	Justin Yoo
 * @package	KYR.Core
 * 
 */
class LogHandler extends BaseHandler
{
	/**
	 * Initiates the LogHandler class.
	 *
	 * @access	public
	 * @param	Request		$request		Request object that contains page request details.
	 * @param	int			$componentID	Component ID.
	 * @param	Exception	$ex				Exception.
	 * @exception							Throws an Exception while checking the handler.
	 *
	 */
	public function __construct($request, $componentID, $ex = null)
	{
		parent::__construct($request, $componentID);
		$this->handlerName	= __CLASS__;

		if (is_null($ex))
		{
			try
			{
				$existHandler = $this->CheckHandler_();
				if (!$existHandler)
					throw new Exception("Handler not found");
			}
			catch (Exception $ex) { throw $ex; }
		}
	}

	/**
	 * Processes handler.
	 *
	 * @access	public
	 * @param	array	$variables	Set of data generated by component.
	 * @exception					Throws an Exception while processing the handler.
	 *
	 */
	public function ProcessHandler(&$variables)
	{
		//	Processes the parent method.
		try { $this->ProcessHandler_($variables); } catch (Exception $ex) { throw $ex; }
		//	Saves log to the file.
		try { $this->_SaveLog($variables["message"]); } catch (Exception $ex) { throw $ex; }
	}
	
	/**
	 * Saves log to a file.
	 *
	 * @access	public
	 * @param	string	$message	Log message to save.
	 * @param	string	$type		Log type.
	 * @exception					Throws an Exception while saving the log to a file.
	 *
	 */
	private function _SaveLog($message, $type = "Web")
	{
		//	Sets the logfile path and name.
		$logFile = LOG_PATH.date("Ymd").".log";
		
		//	Prepends and appends extra information.
		$prepend = "Logged on ".date("d/m/Y H:i:s")." by ".$this->request->user["host"]."(".$this->request->user["ip"].")\n\n";
		$append  = "\n+=========+=========+=========+=========+=========+=========+=========+=========\n\n";
		
		//	Opens and writes to the log file.
		$file = null;
		try
		{
			$file = fopen($logFile, "a");
			fwrite($file, $prepend.$message.$append);
			fclose($file);
		}
		catch (Exception $ex) { throw $ex; }
	}
}
?>
